﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.ZhaoLuService;
using System.IO;
using CommunitySystem.PageView;

namespace CommunitySystem
{
    public partial class ZhengShenWindow : ChildWindow
    {
        private ZhaoLuService.ZhaoLuServiceClient Client1 = new ZhaoLuServiceClient();
        private ZhaoLu_DaoRuKaoShengModel model = new ZhaoLu_DaoRuKaoShengModel();
        private ZhaoLuZhengShen_AttatchmentModel jinshenatt = null;
        public int ID;
        public ZhengShenWindow(int id)
        {
            InitializeComponent();
          
            ID = id;
           // _uploadClient.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(_uploadClient_UploadFileCompleted);
            
            Client1.GetZhaoLu_DaoRuKaoShengModelCompleted += new EventHandler<GetZhaoLu_DaoRuKaoShengModelCompletedEventArgs>(Client1_GetZhaoLu_DaoRuKaoShengModelCompleted);
            
            Client1.UpdateZL_ZhengShenCompleted += new EventHandler<UpdateZL_ZhengShenCompletedEventArgs>(Client1_UpdateZL_ZhengShenCompleted);
            
            Load();
        }
        public void Load()
        {
            Client1.GetZhaoLu_DaoRuKaoShengModelAsync(0, false, 0, ID, "", "", "", null, "", "无", "0");
        }
        void Client1_GetZhaoLu_DaoRuKaoShengModelCompleted(object sender, GetZhaoLu_DaoRuKaoShengModelCompletedEventArgs e)
        {
            if (e.Result != null && e.Result.Count > 0)
                this.DataContext = model = e.Result[0];

            Page(null);
            #region  ////
            //foreach (ZhaoLuZhengShen_AttatchmentModel i in model.Attachment)
            //{

            //    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, };
            //    sp.Children.Add(new TextBlock() { Text = i.realname });
            //    Image img = new Image() { Cursor = Cursors.Hand, Height = 15, Width = 15, Tag = i.ID };
            //    img.Source = new System.Windows.Media.Imaging.BitmapImage(
            //        new Uri("/CommunitySystem;component/Images/ViewDesign/delete.png",
            //            UriKind.RelativeOrAbsolute));
            //    sp.Children.Add(img);
            //    wp.Children.Add(sp);
            //    img.MouseLeftButtonDown += (sender1, e1) =>
            //    {
            //        int id = Convert.ToInt32(((Image)sender1).Tag);
            //        wp.Children.Remove(sp);
            //        model.Attachment.Remove(model.Attachment.Where(p => p.ID == id).FirstOrDefault());
            //    };
            //}
            #endregion
        }

        public string zhengshenresult = "";
        void _uploadClient_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            model.ZhengShenResult = zhengshenresult;
            var file = e.UserState as UploadFileInfo;
            if (file.Context.Count > 0)
            {
                _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], false, file);
                file.Context.RemoveAt(0);
            }
            Client1.UpdateZL_ZhengShenAsync(model);
        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
        private PublicOfficialSelectionService.PublicOfficialSelectionServiceClient _uploadClient =
            new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
        /// <summary>
        /// 政审合格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            zhengshenresult = "合格";
            #region ////
            //if (wp.Children.Count == 0)
            //{
            //    SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传政审表格！");
            //    return;
            //}
            //if (files.Count > 0)
            //{
            //    #region 上传文件
            //    foreach (var key in files.Keys)
            //    {
            //        var file = files[key];
            //        if (file.Context.Count > 0)
            //        {
            //            _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], true, file);
            //            file.Context.RemoveAt(0);
            //        }
                   
            //    }
            //    #endregion
            //}
            //else
            //{
            //    model.ZhengShenResult = zhengshenresult;
            //    Client1.UpdateZL_ZhengShenAsync(model);
            //}


            //if (_files.Count == 0)
            //{
            //    SilverlightMessageBoxLibrary.Message.InfoMessage("No files to upload. Please select one or more files first.");
            //}
            //if (_files.Count!=0)
            //{
            //    _files.UploadFiles();
            //}
            #endregion

          
           if (_files.Count == 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传政审表格！");
                  return;
            }
           if (_files.Where(p => p.State == Constants.FileStates.Uploading).Count() > 0)
           {
               SilverlightMessageBoxLibrary.Message.ErrorMessage("附件正在上传，请稍后！");
               return;
           }
           else
           {
               if (model.Attachment == null)
                   model.Attachment = new System.Collections.ObjectModel.ObservableCollection<ZhaoLuZhengShen_AttatchmentModel>();
               else
                   model.Attachment.Clear();
               foreach (var item in _files.Where(p => p.State == Constants.FileStates.Finished).ToList())
               {
                  
                   var att = new ZhaoLuZhengShen_AttatchmentModel() { realname = item.FileNameG, filename = item.FileName, Key = fileDictionary,Status=(item.State).ToString(),FileSize=item.FileSize.ToString(),Percentage=item.Percentage.ToString() };
                   model.Attachment.Add(att);
               }
               model.ZhengShenResult = zhengshenresult;
               Client1.UpdateZL_ZhengShenAsync(model);
           }
        }
        /// <summary>
        /// 不合格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKButton_Click1(object sender, RoutedEventArgs e)
        {
            zhengshenresult = "不合格";
            #region  ////
            //if (files.Count > 0)
            //{
            //    #region 上传文件
            //    foreach (var key in files.Keys)
            //    {
            //        var file = files[key];
            //        _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], true, file);
            //        file.Context.RemoveAt(0);

            //    }
            //    #endregion
            //}
            //else
            //{
            //    model.ZhengShenResult = zhengshenresult;
            //    Client1.UpdateZL_ZhengShenAsync(model);
            //}
            #endregion


            if (_files.Count == 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传政审表格！");
                  return;
            }
            if (_files.Where(p => p.State == Constants.FileStates.Uploading).Count() > 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("附件正在上传，请稍后！");
                return;
            }
            else
            {
                if (model.Attachment == null)
                    model.Attachment = new System.Collections.ObjectModel.ObservableCollection<ZhaoLuZhengShen_AttatchmentModel>();
                else
                    model.Attachment.Clear();
                foreach (var item in _files.Where(p => p.State == Constants.FileStates.Finished).ToList())
                {
                   
                    var att = new ZhaoLuZhengShen_AttatchmentModel() { realname = item.FileNameG, filename = item.FileName, Key = fileDictionary, Status = (item.State).ToString(), FileSize = item.FileSize.ToString(), Percentage = item.Percentage.ToString() };
                    model.Attachment.Add(att);
                }

                model.ZhengShenResult = zhengshenresult;
                Client1.UpdateZL_ZhengShenAsync(model);
            }

        }
        private int count = 1;
        void Client1_UpdateZL_ZhengShenCompleted(object sender, UpdateZL_ZhengShenCompletedEventArgs e)
        {
            count = count - 1;
            if (count == 0)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("政审成功！");
                this.DialogResult = true;
            }
           
        }
        private readonly string fileDictionary = "file";
        private Dictionary<string, UploadFileInfo> files = new Dictionary<string, UploadFileInfo>();


        private int _maxFileSize = int.MaxValue;

        private FileCollection _files;
        private int _maxUpload = 4;
        private string _customParams;
        private string _fileFilter;
        /// <summary>
        /// 材料上报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hlb_Click(object sender, RoutedEventArgs e)
        {
           
            #region  ////
            //if (Model.Attachment != null)
            //{
            //    if (Model.Attachment.Count > 0)
            //        Model.Attachment.Clear();
            //}


            //var openFile = new OpenFileDialog() { Multiselect = true };
            //if (openFile.ShowDialog() == true)
            //{
               
                //string GuidName = Guid.NewGuid().ToString("N");
                //// files.Add(GuidName, openFile.File.OpenRead());
                //UploadFileInfo uploadFile = new UploadFileInfo() { DisplayName = GuidName, Name = GuidName };
                //var stream = openFile.File.OpenRead();
                //uploadFile.Size = stream.Length / 16000;
                //uploadFile.Context = new List<byte[]>();
                //int b = 0;
                //while (stream.Position > -1 && stream.Position < stream.Length)
                //{
                //    if (stream.Length - stream.Position >= 16000)
                //    {
                //        b = 16000;
                //    }
                //    else
                //    {
                //        b = (int)(stream.Length - stream.Position);
                //    }

                //    byte[] filebyte = new byte[b];
                //    stream.Read(filebyte, 0, b);
                //    uploadFile.Context.Add(filebyte);
                //}
                //stream.Close();
                //files.Add(GuidName, uploadFile);
                //StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = System.Windows.VerticalAlignment.Center };
                //sp.Children.Add(new TextBlock() { Text = openFile.File.Name, });
                //Image img = new Image() { Cursor = Cursors.Hand, Height = 15, Width = 15, Margin = new Thickness(5, 0, 0, 0) };
                //img.Source = new System.Windows.Media.Imaging.BitmapImage(
                //    new Uri("/CommunitySystem;component/Images/ViewDesign/delete.png",
                //        UriKind.RelativeOrAbsolute));
                //sp.Children.Add(img);

                //if (model.Attachment == null)
                //    model.Attachment = new System.Collections.ObjectModel.ObservableCollection<ZhaoLuZhengShen_AttatchmentModel>();
                //var att = new ZhaoLuZhengShen_AttatchmentModel() { realname = openFile.File.Name, filename = GuidName, Key = fileDictionary };
                //model.Attachment.Add(att);
                //jinshenatt = model.Attachment.First();
                //img.MouseLeftButtonDown += (sender1, e1) =>
                //{
                //    wp.Children.Remove(sp);
                //    files.Remove(GuidName);
                //    model.Attachment.Remove(att);
                //    jinshenatt = null;
                //};
                //wp.Children.Add(sp);




            //}
            #endregion
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;

            try
            {
                if (!string.IsNullOrEmpty(_fileFilter))
                    ofd.Filter = _fileFilter;
            }
            catch (ArgumentException ex)
            {
                //User supplied a wrong configuration file
                throw new Exception("Wrong file filter configuration.", ex);
            }

            if (ofd.ShowDialog() == true)
            {
               
                foreach (FileInfo file in ofd.Files)
                {
                    string GuidName = Guid.NewGuid().ToString("N");
                    string fileName = file.Name;

                    UserFile userFile = new UserFile();
                    userFile.FileName = GuidName; //GuidName file.Name;
                    userFile.FileNameG = fileName;
                    userFile.IsAdd = true;
                    userFile.FileStream = file.OpenRead();


                    #region  页面显示
                    //StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, VerticalAlignment = System.Windows.VerticalAlignment.Center };
                    //sp.Children.Add(new TextBlock() { Text = fileName });

                    ////<ProgressBar x:Name="PercentageProgress" Width="30" Value="{Binding Percentage}"></ProgressBar>
                    //ProgressBar pb = new ProgressBar() { Margin=new Thickness(10,0,0,0), Width = 30, Value = userFile.Percentage };
                    //sp.Children.Add(pb);
                    
                    //Image img = new Image() { Cursor = Cursors.Hand, Height = 15, Width = 15, Margin = new Thickness(5, 0, 0, 0) };
                    //img.Source = new System.Windows.Media.Imaging.BitmapImage(
                    //    new Uri("/CommunitySystem;component/Images/ViewDesign/delete.png",
                    //        UriKind.RelativeOrAbsolute));

                    //sp.Children.Add(img);

                    //if (model.Attachment == null)
                    //    model.Attachment = new System.Collections.ObjectModel.ObservableCollection<ZhaoLuZhengShen_AttatchmentModel>();
                    //var att = new ZhaoLuZhengShen_AttatchmentModel() { realname = fileName, filename = GuidName, Key = fileDictionary };

                    foreach (var item in _files)
                    {
                        if (item.FileNameG.Contains(fileName))
                        {
                            SilverlightMessageBoxLibrary.CustomMessage cm = new SilverlightMessageBoxLibrary.CustomMessage("此文件已上传,需要覆盖原有文件吗?", SilverlightMessageBoxLibrary.CustomMessage.MessageType.Confirm, null);
                            cm.Show();
                            cm.OKButton.Click += (sender1, e1) =>
                            {
                               // model.Attachment.Remove(item);
                                // wp.Children.Remove(sp);
                                _files.Remove(item);
                            };
                        }
                    }

                    //model.Attachment.Add(att);
                    //jinshenatt = model.Attachment.First();
                    //img.MouseLeftButtonDown += (sender1, e1) =>
                    //{
                    //    wp.Children.Remove(sp);
                    //    _files.Remove(userFile);
                    //    model.Attachment.Remove(att);
                    //    jinshenatt = null;
                    //};
                    //wp.Children.Add(sp);
                    #endregion

                    if (userFile.FileStream.Length <= _maxFileSize)
                    {
                        //向文件列表中添加文件信息
                        if(_files==null)  _files = new FileCollection(_customParams, _maxUpload);
                        _files.Add(userFile);
                    }
                    else
                        SilverlightMessageBoxLibrary.Message.InfoMessage("上传最大文件大小：" + (_maxFileSize / 1024).ToString() + "KB.");
                }
            }

        }


         public void Page(IDictionary<string, string> initParams)
        {
            _files = new FileCollection(_customParams, _maxUpload);
            if (model.Attachment != null)
            {
                if (model.Attachment.Count > 0)
                {
                    foreach (var item in model.Attachment)
                    {
                        var uf = new UserFile() { FileName=item.filename, FileNameG = item.realname, State = Constants.FileStates.Finished, Percentage = Convert.ToInt32(item.Percentage), BytesUploaded = Convert.ToDouble(item.FileSize), FileSize = Convert.ToDouble(item.FileSize) };
                     
                        _files.Add(uf);
                    }
                }
            }
           
            FileList.ItemsSource = _files;
          
        }
    
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ibtnFJ_Click(object sender, RoutedEventArgs e)
        {
            if (_files.Count == 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传政审表格！");
                  return;
            }
            else 
            {
                this.OKButton.IsEnabled = true;
                this.NoOKButton.IsEnabled = true;
                _files.UploadFiles();
            }
        }
    }
}
